﻿using McsWeb.API.ZBAPI;
using McsWeb.Models;
using McsWeb.Models.ZBModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace McsWeb.Common
{
    public class Tools
    {

        private MarketsAPI marketsAPI = new MarketsAPI();
         
        /// <summary>
        /// 获取行情
        /// </summary>
        /// <returns></returns>
        public static MarketsListModel GetTickerModel(string coin)
        {
            MarketsListModel model = new MarketsListModel();
            model.name = "中币网";

            try
            {
                Ticker res = MarketsAPI.GetTicker(coin);

                if (res == null || res.ticker == null)
                {
                    return null;
                }

                model.last = res.ticker.last;
                model.sell = res.ticker.sell;
                model.buy = res.ticker.buy;
                model.high = res.ticker.high;
                model.low = res.ticker.low;
                model.vol = res.ticker.vol;
                model.time = TimestampHelper.TimestampToDateTime(res.date);

                return model;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
         
        public static int GetUrlPurse(string address, string startblock)
        {
            string sHtmlText = GetUrl("http://api.etherscan.io/api?module=account&action=txlist&address=" + address + "&startblock=" + startblock + "&endblock=99999999&sort=asc&apikey=FAES9K2QJZD4S1KD4U3XY2PDJR6C8289ES");

            PruseModel pm = JsonConvert.DeserializeObject<PruseModel>(sHtmlText);
            int count = 0;
            foreach (Result item in pm.Result)
            {
                if (Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.GetSingle("select count(*) from PumpWalletRunnings where Hash='" + item.Hash + "'")) == 0)
                {
                    string sql = "insert into PumpWalletRunnings values('" + item.BlockNumber + "','" + item.TimeStamp + "','" + item.Hash + "','" + item.Nonce + "','" + item.BlockHash + "','" + item.TransactionIndex + "','" + item.From + "','" + item.To + "','" + item.Value + "','" + item.Gas + "','" + item.GasPrice + "','" + item.IsError + "','" + item.Txreceipt_status + "','" + item.Input + "','" + item.ContractAddress + "','" + item.CumulativeGasUsed + "','" + item.GasUsed + "','" + item.Confirmations + "')";
                    count = Convert.ToInt32(FangChan.DBUtility.DbHelperSQL.ExecuteSql(sql));
                }
            }

            return count;
        }

        public static string GetUrl(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));

            return reader.ReadToEnd();
        }

        public static bool PumpWalletAsync()
        {
            DataTable dt = FangChan.DBUtility.DbHelperSQL.Query("select * from PumpWallets where Currencys='eth'").Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                string startblock = FangChan.DBUtility.DbHelperSQL.GetSingle("select isnull(max(CONVERT(int, blockNumber)), 0) from PumpWalletRunnings where [to] = '"+item["Address"].ToString() +"'").ToString();
                GetUrlPurse(item["Address"].ToString(), startblock);
            }
            return true;
        }
    }
}